package org.leon.controller;

import org.leon.pojo.Article;
import org.leon.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@Controller
public class BlogSystemController {

    private ArticleService articleService;

    @Autowired
    public BlogSystemController(ArticleService articleService) {
        this.articleService = articleService;
    }

    @GetMapping("/health/check")
    @ResponseBody
    public String hello() {
        return "hello";
    }

    /**
     * 重定向到首页
     */
    @RequestMapping("/")
    public void index(HttpServletResponse response) {
        try {
            response.sendRedirect("/index");
        } catch (IOException e) {}
    }


    /**
     * 分页查询
     * @param model 返回页码的数据 model
     * @param pageNum 分页页码，从 1 开始 （注入 jpa 的分页从 0 开始）
     */
    @RequestMapping("/index")
    public String blogList(Model model, Integer pageNum) {

        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }

        model.addAttribute("hasPreviousPage", true);
        model.addAttribute("hasNextPage", true);

        // 如果当前是第一页，则没有上一页
        if (pageNum == 1) {
            model.addAttribute("hasPreviousPage", false);
        }

        Page<Article> articles = articleService.findArticleByPage(pageNum);

        // 如果当前请求页是最后一页，则通知页面：没有下一页
        int totalPages = articles.getTotalPages();
        if (pageNum >= totalPages) {
            model.addAttribute("hasNextPage", false);
            pageNum = totalPages;
        }

        model.addAttribute("articleList", articles.getContent());
        model.addAttribute("pageNum", pageNum);
        return "client/index";
    }



}
